package mr.ali.videoapp.portal.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wx")
public class wxApiUrlController {

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String URLLINK_URL = "https://api.weixin.qq.com/wxa/generate_urllink";
    private final String appId = "wx68b7ece486eb3e32";
    private final String appSecret = "d64374fdafaca0a7275dd96b19bf2c68";
    // 简单缓存 access_token
    private String accessToken = "";
    private long expiresTime = 0;

    @PostMapping("/urllink")
    public ResponseEntity<Map<String, String>> getUrlLink(@RequestParam String page, @RequestParam(required = false) String query) {

        try {
            // 1. 获取 access_token
            String token = getAccessToken();
            if (token == null) {
                return error("获取 access_token 失败");
            }

            // 2. 构建请求体
            JSONObject json = new JSONObject();
            json.put("page", page);           // 页面路径
            if (query != null && !query.isEmpty()) {
                json.put("query", query);     // 参数，如 id=1001
            }
            json.put("is_expire", false);     // 是否过期（false = 永久有效）
            json.put("env_version", "release"); // online 环境

            // 3. 调用生成接口
            HttpPost httpPost = new HttpPost(URLLINK_URL + "?access_token=" + token);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(json.toJSONString(), "UTF-8"));

            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpResponse resp = client.execute(httpPost);
                String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
                JSONObject resJson = JSON.parseObject(result);

                if (resJson.getIntValue("errcode") == 0) {
                    Map<String, String> data = new HashMap<>();
                    data.put("url", resJson.getString("url_link"));
                    return ResponseEntity.ok(data);
                } else {
                    return error("生成失败: " + resJson.getString("errmsg"));
                }
            }
        } catch (Exception e) {
            return error("系统错误: " + e.getMessage());
        }
    }

    private synchronized String getAccessToken() {
        if (System.currentTimeMillis() < expiresTime) {
            return accessToken;
        }
        try {
            String url = TOKEN_URL +
                    "?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpResponse resp = client.execute(httpGet);
                String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
                JSONObject json = JSON.parseObject(result);
                accessToken = json.getString("access_token");
                expiresTime = System.currentTimeMillis() + (json.getLong("expires_in") - 60) * 1000;
                return accessToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private ResponseEntity<Map<String, String>> error(String msg) {
        Map<String, String> data = new HashMap<>();
        data.put("error", msg);
        return ResponseEntity.status(500).body(data);
    }
}